package com.sinodata.bsm.center.web.action.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.adventnet.snmp.ui.DieInterface;
import com.ibm.db2.jcc.b.p;
import com.sinodata.bsm.center.bean.Condition;
import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.cache.DimensionCache;
import com.sinodata.bsm.center.cache.DimensionTypeCache;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.config.DimensionService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.utils.StringUtil;
import com.sinodata.bsm.common.vo.Dimension;
import com.sinodata.bsm.common.vo.DimensionType;
import com.sinodata.bsm.common.vo.RelationType;

public class DimensionConfigAction extends BaseAction<Dimension> {

    @Autowired
    private DimensionService dimensionService;
    @Autowired
    private DimensionCache dimensionCache;
    @Autowired
    private DimensionTypeCache dimensionTypeCache;

    private Dimension dimension;

    private Long[] ids;
    private Long id;

    public String common() {
        String dimensionTypeid = request.getParameter("dimensionTypeId");
        DimensionType dimensionType = dimensionTypeCache.get(Long.valueOf(dimensionTypeid));
        Struts2Utils.setRequestAttribute("dimensionType", dimensionType);
        return "common";
    }

    public String add() {
        try {
            String dimensionTypeId = request.getParameter("dimensionTypeId");
            DimensionType dimensionType = dimensionTypeCache.get(Long.valueOf(dimensionTypeId));
            if (dimensionType.getIsRelation().longValue() == 0) {
                List<Dimension> dimensionList = getDimensionList(dimension);
                Struts2Utils.getRequest().setAttribute("dimensionList", dimensionList);
            }
            Struts2Utils.setRequestAttribute("dimensionType", dimensionType);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return "add";
    }

    public String validateDimensionName() {
        if ("true".equals(request.getParameter("isValideFlag"))) {
            Condition condition = new Condition();
            Map<String, String> map = new HashMap<String, String>();
            map.put("dimensionName", "'" + request.getParameter("dimensionName") + "'");
            condition.setWhere(map);
            int count = dimensionService.getTotal(condition);
            if (count == 0) {
                renderText("true");
            } else {
                renderText("false");
            }
        } else {
            renderText("true");
        }
        return null;
    }

    @Override
    public String delete() throws Exception {
        try {
            // TODO Auto-generated method stub
            for (Long id : ids) {
                if (dimensionCache.get(id) == null) {
                    renderText("false");
                    return null;
                }
            }
            dimensionService.deleteDimension(ids);
            for (Long id : ids) {
                dimensionCache.remove(id);
            }
            renderText("true");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String input() throws Exception {
        // TODO Auto-generated method stub
        Dimension dimension = dimensionCache.get(Long.valueOf(request.getParameter("id")));
        DimensionType dimensionType = dimensionTypeCache.get(dimension.getDimensionTypeId());
        Dimension dimensionParent = dimensionCache.get(dimension.getParentId());

        Struts2Utils.getRequest().setAttribute("dimensionType", dimensionType);
        Struts2Utils.getRequest().setAttribute("dimension", dimension);
        if (dimensionType.getIsRelation().longValue() == 0) {
            List<Dimension> dimensionList = getDimensionList(dimension);
            Struts2Utils.getRequest().setAttribute("dimensionList", dimensionList);
        }
        Struts2Utils.getRequest().setAttribute("dimensionParent", dimensionParent);

        return "update";
    }

    public List<Dimension> getDimensionList(Dimension dimension) {
        List<Dimension> dimensionList = new ArrayList<Dimension>();
        for (Dimension d : dimensionCache.getAll()) {
            if (dimension != null) {
                if (d.getId().equals(dimension.getId())) {
                    continue;
                }
                if (d.getId().equals(dimension.getParentId())) {
                    continue;
                }
            }
            dimensionList.add(d);
        }
        return dimensionList;
    }

    @Override
    public String list() throws Exception {
        // TODO Auto-generated method stub
        try {
            // TODO Auto-generated method stub
            String dimensionName = request.getParameter("dimensionName");
            String dimensionTypeId = request.getParameter("dimensionTypeId");
            Condition condition = new Condition();
            Map<String, String> map = new HashMap<String, String>();
            if (!StringUtil.isEmpty(dimensionName)) {
                map.put("dimensionName", "'" + dimensionName + "'");
            }
            if (!StringUtil.isEmpty(dimensionTypeId)) {
                map.put("dimensionTypeId", "'" + dimensionTypeId + "'");
            }
            // 分页排序
            Map<String, String> orderMap = new HashMap<String, String>();
            String order = request.getParameter("sSortDir_0");
            String col = request.getParameter("mDataProp_" + request.getParameter("iSortCol_0"));
            if (!col.equals("checkbox") && !col.equals("op")) {
                orderMap.put(col, order);
            }
            condition.setWhere(map);
            // 分页参数
            Page<Dimension> page = new Page<Dimension>();
            page.setPageNo(Integer.valueOf(request.getParameter("iDisplayStart")) / Integer.valueOf(request.getParameter("iDisplayLength")) + 1);
            page.setPageSize(Integer.valueOf(request.getParameter("iDisplayLength")));
            // 分页数据
            Page<Dimension> dimensionPage = dimensionService.findByPage(page, condition);
            // Json数据的封装
            JSONObject json = new JSONObject();
            json.element("iTotalRecords", page.getTotal());
            json.element("iTotalDisplayRecords", page.getTotal());
            JSONArray array = new JSONArray();
            boolean sysManager = UserFunctionValidate.sysFunctionValidate(FunctionConstants.SYSTEM_MANAGER);
            for (Dimension dimension : dimensionPage.getRows()) {
                JSONObject obj = new JSONObject();
                obj.element("checkbox", "<div align='center'><input type='checkbox' name='dt_check' id='dt_check' value='" + dimension.getId() + "'></div>");
                if (sysManager) {
                    obj.element("op", "<div style='width: 80px'>&nbsp;&nbsp;<a href='javascript:edit(" + dimension.getId() + ");'><img src='../style/default/bsm/images/edit.gif' title='修改'></a>&nbsp;<a href='javascript:deleteOne(" + dimension.getId() + ");'><img src='../style/default/bsm/images/delete.gif' title='删除'></a>&nbsp;<a href='javascript:test(" + dimension.getId() + ");'><div>");
                } else {
                    obj.element("op", "<div style='width: 80px'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:test(" + dimension.getId() + ");'><img src='../style/default/bsm/images/test.gif' title='修改'></a><div>");
                }
                obj.element("id", dimension.getId());
                obj.element("dimensionName", dimension.getDimensionName());
                Dimension parentDimension = dimensionCache.get(dimension.getParentId());
                obj.element("parentId", parentDimension != null ? parentDimension.getDimensionName() : "");
                obj.element("dimensionstate", dimension.getDimensionState() == 0 ? "正常" : "禁用");
                array.add(obj);
            }
            json.element("aaData", array);
            renderText(json.toString());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {
        // TODO Auto-generated method stub
        if (id != null) {
            dimension = dimensionCache.get(id);
            if (dimension == null) {
                dimension = new Dimension();
            }
        } else {
            dimension = new Dimension();
        }
    }

    @Override
    public String save() throws Exception {
        try {
            // TODO Auto-generated method stub
            // 修改
            if (dimension.getId() != null) {
                if (dimensionCache.get(dimension.getId()) != null) {
                    Dimension updateDimension = dimensionCache.get(dimension.getId());
                    updateDimension.setDimensionName(dimension.getDimensionName());
                    updateDimension.setParentId(dimension.getParentId());
                    dimensionService.update(updateDimension);
                    dimensionCache.put(updateDimension.getId(), updateDimension);
                }
            } else { // 增加
                dimensionService.add(dimension);
                dimensionCache.put(dimension.getId(), dimension);
            }
            renderText("true");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    public String checkDeleted() {
        JSONObject ob = new JSONObject();
        if (dimensionCache.get(id) == null) {
            ob.element("flag", false);
        } else {
            ob.element("flag", true);
        }
        Struts2Utils.renderJson(ob.toString());
        return null;
    }

    public String dimensionTree() {
        try {
            Long dimensionId = request.getParameter("dimensionId") != null ? Long.valueOf(request.getParameter("dimensionId")) : null;
            Map<Long, List<Dimension>> map = new LinkedHashMap<Long, List<Dimension>>();
            List<Dimension> dimensions = dimensionCache.getAll();
            List<Dimension> roots = new ArrayList<Dimension>();
            for (Dimension dimension : dimensions) {
                List<Dimension> list = null;
                if (dimensionId != null) {
                    if (dimension.getId().longValue() == dimensionId.longValue()) {
                        continue;
                    }
                    if (dimension.getParentId() != null && dimension.getParentId().equals(dimensionId)) {
                        continue;
                    }
                }
                if (dimension.getParentId() == null) {
                    roots.add(dimension);
                } else {
                    if (map.get(dimension.getParentId().longValue()) == null) {
                        list = new ArrayList<Dimension>();
                        map.put(dimension.getParentId(), list);
                    }
                    if (dimension.getParentId() != null) {
                        list = map.get(dimension.getParentId().longValue());
                        list.add(dimension);
                    }
                }
            }
            JSONArray jsonArray = new JSONArray();
            JSONObject rootJsonObject = new JSONObject();
            rootJsonObject.element("id", "");
            rootJsonObject.element("name", "设为顶级节点");
            rootJsonObject.element("parentId", "");
            for (Dimension d : roots) {
                jsonArray.add(makeChildren(map, d));
            }
            Struts2Utils.renderText(jsonArray.toString());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;

    }

    private JSONObject makeChildren(Map<Long, List<Dimension>> map, Dimension parent) {
        Long pid = parent.getId();
        List<Dimension> childDimension = map.get(pid);
        JSONObject json = new JSONObject();
        json.element("id", pid);
        json.element("name", parent.getDimensionName());
        json.element("parentId", parent.getParentId());
        JSONArray jsonArray = new JSONArray();
        if (childDimension != null && childDimension.size() > 0) {
            for (Dimension d : childDimension) {
                jsonArray.add(makeChildren(map, d));
            }
        }
        json.element("open", true);
        json.element("children", jsonArray);
        return json;
    }

    @Override
    public Dimension getModel() {
        // TODO Auto-generated method stub
        return this.dimension;
    }

    public Long[] getIds() {
        return ids;
    }

    public void setIds(Long[] ids) {
        this.ids = ids;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}
